using Microsoft.EntityFrameworkCore;
using MESData.ErrorCode;
using MESData.ProductionPlan.API.DTO;
using MESData.Infrastucture;

namespace MESData.ProductionPlan.API.Services
{
    /// <summary>
    /// 物品服务实现类
    /// </summary>
    public class ItemService : IItemService
    {
        private readonly MyDbcontext _context;

        public ItemService(MyDbcontext context)
        {
            _context = context;
        }

        /// <summary>
        /// 根据物品ID查询对应的仓库名称和库存
        /// </summary>
        public async Task<ApiResult<List<ItemInventoryDto>>> GetItemInventoriesAsync(int itemId)
        {
            try
            {
                // 检查物品是否存在
                var item = await _context.Items
                    .FirstOrDefaultAsync(i => i.Id == itemId && !i.IsDeleted);
                
                if (item == null)
                {
                    return new ApiResult<List<ItemInventoryDto>>
                    {
                        Code = ApiEnum.Error,
                        Msg = "物品不存在",
                        Data = null
                    };
                }

                // 查询库存信息
                var inventories = await _context.ItemInventories
                    .Where(ii => !ii.IsDeleted && ii.ItemId == itemId)
                    .Select(ii => new ItemInventoryDto
                    {
                        WarehouseName = ii.WarehouseName,
                        Quantity = (int)ii.Quantity,
                        Status = ii.Status
                    })
                    .ToListAsync();

                return new ApiResult<List<ItemInventoryDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    Data = inventories
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<ItemInventoryDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = $"查询失败：{ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 查询所有物品的分页显示
        /// </summary>
        public async Task<ApiPageing<ItemResultDto>> GetItemsAsync(ItemQueryDto queryDto)
        {
            try
            {
                var query = _context.Items
                    .Where(i => !i.IsDeleted && i.IsActive)
                    .AsQueryable();

                // 应用查询条件
                if (!string.IsNullOrEmpty(queryDto.ItemNumberOrNameOrModel))
                {
                    query = query.Where(i => 
                        i.ItemNumber.Contains(queryDto.ItemNumberOrNameOrModel) ||
                        i.ItemName.Contains(queryDto.ItemNumberOrNameOrModel) ||
                        i.SpecificationModel.Contains(queryDto.ItemNumberOrNameOrModel));
                }

                if (!string.IsNullOrEmpty(queryDto.ItemCategory))
                {
                    query = query.Where(i => i.ItemCategory == queryDto.ItemCategory);
                }

                if (!string.IsNullOrEmpty(queryDto.ItemClassification))
                {
                    query = query.Where(i => i.ItemClassification == queryDto.ItemClassification);
                }

                // 获取总数
                var totalCount = await query.CountAsync();

                // 分页查询（TotalInventory 使用可翻译的子查询计算）
                var items = await query
                    .OrderBy(i => i.ItemNumber)
                    .Skip((queryDto.PageIndex - 1) * queryDto.PageSize)
                    .Take(queryDto.PageSize)
                    .Select(i => new ItemResultDto
                    {
                        Id = i.Id,
                        ItemNumber = i.ItemNumber,
                        ItemName = i.ItemName,
                        SpecificationModel = i.SpecificationModel,
                        Unit = i.Unit,
                        ItemCategory = i.ItemCategory,
                        ItemClassification = i.ItemClassification,
                        Brand = i.Brand,
                        TotalInventory = _context.ItemInventories
                            .Where(ii => !ii.IsDeleted && ii.ItemId == i.Id)
                            .Select(ii => (int?)ii.Quantity)
                            .Sum() ?? 0,
                        PurchaseUnitPrice = i.PurchaseUnitPrice,
                        SalesUnitPrice = i.SalesUnitPrice
                    })
                    .ToListAsync();

                var totalPage = (int)Math.Ceiling((double)totalCount / queryDto.PageSize);

                return new ApiPageing<ItemResultDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    TotaCount = totalCount,
                    TotaPage = totalPage,
                    PageData = items
                };
            }
            catch (Exception ex)
            {
                return new ApiPageing<ItemResultDto>
                {
                    Code = ApiEnum.Error,
                    Msg = $"查询失败：{ex.Message}",
                    Data = null,
                    TotaCount = 0,
                    TotaPage = 0,
                    PageData = null
                };
            }
        }
    }
} 